<template>
  <el-main v-loading="pageLoading" style="padding: 0">
    <div class="h-screen">
      <div class="login-container animate__animated" :class="{ device }" :style="bg">
        <div
          v-if="!pageLoading"
          class="login-content animate__animated"
          :class="{ animate__zoomOut: outClass, animate__fadeIn: !outClass }"
          :style="{ borderRadius: config.borderRadius + 'px' }"
        >
          <!-- 左侧图片展示区域 -->
          <div v-if="config.custom_left >= 0" class="login-image animate__animated animate__fadeIn">
            <div v-if="config.custom_left === '0'" class="default-login-img">
              <img width="100%" alt="" :src="leftImg" class="min-h-50" />
              <h2>{{ config.site_name }}</h2>
              <p>快速创建属于自己的SaaS</p>
            </div>
            <div v-else class="default-login-img" v-html="config.left_content" />
          </div>

          <!-- 登录表单 -->
          <div class="login-form animate__animated animate__fadeIn">
            <el-form
              ref="loginFormRef"
              size="large"
              :model="loginData"
              :rules="loginRules"
              class="form-content"
              auto-complete="on"
              label-position="top"
            >
              <div class="login-title">
                <h2>
                  欢迎使用<b>{{ config.site_name }}</b>
                </h2>
                <p v-html="slogan" />
              </div>

              <el-form-item prop="username" label="用户名">
                <el-input
                  ref="usernameRef"
                  v-model="loginData.username"
                  placeholder="请输入登录昵称或手机号"
                  name="username"
                  type="text"
                  tabindex="1"
                  auto-complete="on"
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-form-item prop="password" label="密码">
                <el-input
                  :key="passwordType"
                  ref="passwordRef"
                  v-model="loginData.password"
                  :type="passwordType"
                  placeholder="请输入登录密码"
                  name="password"
                  tabindex="2"
                  auto-complete="on"
                  show-password
                  @keyup.enter="handleLogin"
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <p>
                <el-checkbox v-model="loginData.remember" class="mb-5">记住账号与密码</el-checkbox>
                <span class="float-right cursor-pointer" @click="forgetPassword">忘记密码</span>
              </p>

              <el-button :loading="loading" type="primary" class="w-full mb-7" @click.prevent="handleLogin"> 登录 </el-button>
            </el-form>
          </div>
        </div>

        <!-- 页脚 -->
        <div class="login-footer px-2">
          <p v-if="config.icp" class="mb-1">
            <a href="https://beian.miit.gov.cn/" target="_blank" class="color-#999">{{ config.icp }}</a>
          </p>
          <p v-if="config.copyright">{{ config.copyright }}</p>
        </div>
      </div>
    </div>
  </el-main>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Lock, User } from '@element-plus/icons-vue'
import { login } from '@/api/user'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useSettingsStore } from '@/stores/settings'
import { useDevice } from '@/composables/useDevice'

defineOptions({ name: 'Login' })

// refs
const loginFormRef = ref()
const usernameRef = ref()
const passwordRef = ref()

// state
const loading = ref(false)
const pageLoading = ref(true)
const outClass = ref(false)
const passwordType = ref('password')
const redirect = ref(undefined)

// 登录配置
const config = ref({
  site_name: '多客管理系统',
  slogan: '这是一句好听顺嘴而且不长不短刚刚好的Slogan<br>甚至可以写第二行',
  icp: '',
  copyright: '',
  bg_image: '',
  bg_color: '',
  borderRadius: 20,
  custom_left: '0',
  left_content: '',
  l_image: '',
  title: '多客管理系统'
})

// 登录表单数据
const loginData = ref({
  username: '',
  password: '',
  remember: false
})

// 表单验证规则
const loginRules = {
  username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
}

// stores and composables
const userStore = useUserStore()
const settingsStore = useSettingsStore()
const route = useRoute()
const router = useRouter()
const { device } = useDevice()

const leftImg = computed(() => {
  return config.value.l_image || new URL('@/assets/default/login-rafiki.svg', import.meta.url).href
})

const bg = computed(() => {
  const style = {
    backgroundImage: '',
    backgroundRepeat: 'no-repeat',
    backgroundSize: 'cover',
    backgroundColor: ''
  }

  if (config.value.bg_image) {
    style.backgroundImage = `url(${config.value.bg_image})`
  } else {
    // 使用默认背景
    const defaultBg = new URL('@/assets/default/login-bg.webp', import.meta.url).href
    style.backgroundImage = `url(${defaultBg})`
  }

  if (config.value.bg_color) {
    style.backgroundColor = config.value.bg_color
  }

  return style
})

const slogan = computed(() => {
  return config.value.slogan || '这是一句好听顺嘴而且不长不短刚刚好的Slogan<br>甚至可以写第二行'
})

// watchers
watch(
  () => route.query,
  (query) => {
    redirect.value = query && query.redirect
  },
  { immediate: true }
)

watch(
  () => config.value.title,
  (title) => {
    if (title) {
      document.title = title
    }
  }
)

// methods
/**
 * 忘记密码处理
 */
function forgetPassword() {
  ElMessageBox.alert('请联系管理员找回密码。')
}

/**
 * 登录处理
 */
function handleLogin() {
  loginFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      userStore
        .login(loginData.value)
        .then(() => {
          outClass.value = true
          setTimeout(() => {
            router.push({ path: redirect.value || '/' })
          }, 500)
          loading.value = false
        })
        .catch((error) => {
          console.log(error)
          loading.value = false
        })
    } else {
      return false
    }
  })
}

// lifecycle
onMounted(() => {
  // 获取登录配置
  const loginConfig = settingsStore.login
  if (loginConfig.is_get) {
    config.value = { ...config.value, ...loginConfig }
    pageLoading.value = false
  } else {
    setTimeout(() => {
      settingsStore
        .getLogin()
        .then((res) => {
          config.value = { ...config.value, ...res }
          pageLoading.value = false
        })
        .catch(() => {
          pageLoading.value = false
        })
    }, 1)
  }
})
</script>

<style lang="scss" scoped>
div {
  transition: all 0.5s ease 0s;
}

.login-container {
  display: flex;
  align-items: center;
  height: 100vh;
  justify-content: center;
  flex-direction: column;

  .login-content {
    border-radius: 20px;
    box-shadow: 0 2px 20px #00000033;
    display: flex;
    position: relative;
    background: #fff;
    overflow: hidden;
    height: 600px;

    .login-image {
      width: 500px;
      display: flex;

      .default-login-img {
        width: 100%;
        text-align: center;
        background: #fafafa;
        display: flex;
        flex-direction: column;
        justify-content: center;

        h2 {
          color: #999;
        }

        p {
          color: #aaa;
        }
      }
    }

    .login-form {
      width: 500px;
      display: flex;
      align-items: center;
      justify-content: center;

      .form-content {
        width: 400px;

        .login-title {
          h2 {
            font-weight: 500;
            font-size: 24px;
            padding: 10px 0;
          }

          p {
            color: #98a6ad;
            padding: 10px 0;
          }
        }
      }
    }
  }
}

@media screen and (max-width: 1000px) {
  .login-image {
    display: none !important;
  }
}

@media screen and (max-width: 500px) {
  .login-content {
    width: 100%;
    padding: 20px;
    text-align: center;
    height: 100vh !important;
    border-radius: 0px !important;

    .login-form {
      width: 100% !important;

      .form-content {
        width: 100% !important;
      }
    }
  }
}

.login-footer {
  font-size: 14px;
  text-align: center;
  position: fixed;
  bottom: 10px;
  color: #999;
}
</style>
